// 在多线程中回调定时器函数，用 mutex 保护共享变量。
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/base/Mutex.h>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <iostream>

using namespace muduo;
using namespace muduo::net;
using namespace std;

class Printer : boost::noncopyable {
public:
	Printer(EventLoop *loop1, EventLoop *loop2)
		: loop1_(loop1), loop2_(loop2), count_(0) {
		loop1_->runAfter(1, boost::bind(&Printer::Print1, this));
		loop2_->runAfter(1, boost::bind(&Printer::Print2, this));
	}

	~Printer() {
		cout << "final count is " << count_ << endl;
	}

private:
	void Print1() {
		MutexLockGuard lock(mutex_);
		if (count_ < 10) {
			cout << "timer1****** " << count_ << endl;
			++count_;
			loop1_->runAfter(1, boost::bind(&Printer::Print1, this));
		} else {
			loop1_->quit();
		}
	}

	void Print2() {
		MutexLockGuard lock(mutex_);
		if (count_ < 10) {
			cout << "timer2****** " << count_ << endl;
			++count_;
			loop2_->runAfter(1, boost::bind(&Printer::Print2, this));
		} else {
			loop2_->quit();
		}
	}

	EventLoop *loop1_;
	EventLoop *loop2_;
	MutexLock mutex_;
	int count_;
};

int 
main() {
	boost::scoped_ptr<Printer> printer;
	EventLoop loop;
	EventLoopThread loopThread;
	EventLoop *loopInAnotherThread = loopThread.startLoop();
	printer.reset(new Printer(&loop, loopInAnotherThread));
	loop.loop();
	return 0;
}